import { Button, Input, message, Popconfirm, Table, TableColumnProps, Tooltip } from "antd";
import { PlusOutlined, DeleteOutlined } from "@ant-design/icons";
import { forwardRef, ForwardRefRenderFunction, useCallback, useImperativeHandle, useMemo, useState } from "react";
import { cloneDeep } from "lodash";
interface ExtraRecord {
	_key: string;
	_value: string;
}
interface ExtraTableProps {
	reflectExtra: (data: ExtraRecord[]) => void;
}
export interface ExtraTableRef {
	// eslint-disable-next-line @typescript-eslint/no-explicit-any
	initValues: (extra?: Record<string, any>) => void;
}
const ExtraTable: ForwardRefRenderFunction<ExtraTableRef, ExtraTableProps> = ({ reflectExtra }, ref) => {
	const getInitialDataSource = () => [{ _key: "", _value: "" }];
	const [dataSource, setDataSource] = useState<ExtraRecord[]>(getInitialDataSource());
	useImperativeHandle(ref, () => ({
		initValues(extra) {
			try {
				if (extra) {
					setDataSource(Object.entries(extra).map(([_key, _value]) => ({ _key, _value })));
				} else {
					setDataSource(getInitialDataSource());
				}
			} catch {
				setDataSource(getInitialDataSource());
			}
		},
	}));
	const changeDataItem = useCallback(
		(item: Partial<ExtraRecord>, index: number) => {
			const copiedData = cloneDeep(dataSource);
			copiedData[index] = { ...copiedData[index], ...item };
			setDataSource(copiedData);
			reflectExtra(copiedData);
		},
		[dataSource]
	);
	const columns = useMemo<TableColumnProps<ExtraRecord>[]>(
		() => [
			{
				title: "键",
				width: "160px",
				dataIndex: "_key",
				render: (text, _, index) => <Input placeholder="请填入属性名" value={text} onChange={e => changeDataItem({ _key: e.target.value }, index)} />,
			},
			{
				title: "值",
				width: "160px",
				dataIndex: "_value",
				render: (text, _, index) => <Input placeholder="请填入属性值" value={text} onChange={e => changeDataItem({ _value: e.target.value }, index)} />,
			},
			{
				title: "操作",
				width: "20px",
				render: (_, _1, index) => (
					<div className="flex">
						<Tooltip title="在下面插入一列">
							<Button
								onClick={() => {
									const copiedData = cloneDeep(dataSource);
									copiedData.splice(index + 1, 0, { _key: "", _value: "" });
									setDataSource(copiedData);
									reflectExtra(copiedData);
								}}
								size="small"
								shape="circle"
								icon={<PlusOutlined />}
							/>
						</Tooltip>
						{index !== 0 && (
							<Popconfirm
								title="确认删除吗？"
								onConfirm={() => {
									const copiedData = cloneDeep(dataSource);
									copiedData.splice(index, 1);
									setDataSource(copiedData);
									reflectExtra(copiedData);
									message.success("已删除");
								}}
							>
								<Button danger size="small" className="ml-2" shape="circle" icon={<DeleteOutlined />} />
							</Popconfirm>
						)}
					</div>
				),
			},
		],
		[dataSource]
	);
	return <Table columns={columns} pagination={false} dataSource={dataSource.map((item, index) => ({ ...item, key: index.toString() }))} />;
};

export default forwardRef(ExtraTable);
